package com.coldworks.coldjoke.manager;

import java.util.List;
import java.util.Observable;

import org.apache.http.client.CookieStore;
import org.apache.http.cookie.Cookie;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.coldworks.base.manager.BasePrefManager;
import com.coldworks.base.util.BaseCONST;
import com.coldworks.coldjoke.task.LoginTask;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Handler;
import android.os.Message;

public class UserManager {
	protected final Logger log = LoggerFactory.getLogger(this.getClass());
	private static UserManager instance = null;

	private LoginTask loginTask;
	private Handler handler;

	public static final int UNLOGINED = 0;
	public static final int LOGINED = 1;
	public static final int LOGIN_SUCC = 2;
	public static final int LOGIN_FAIL = 3;
	private int state = UNLOGINED;

	private String userEmail;
	private String userPassword;
	private String userName;
	private String userId;
	private String userIcon;
	private String sessionId;
	private String rememberMe;
	private boolean isAutoLogin;

	private Context context;

	public static UserManager getInstance() {
		if (instance == null) {
			synchronized (UserManager.class) {
				if (instance == null) {
					instance = new UserManager();
				}
			}
		}
		return instance;
	}

	private UserManager() {

	}

	// 登录时初始化数据
	public void initData(Context context) {
		this.context = context;
		userEmail = BasePrefManager.getInstance().getStringFromPrefs(context,
				BaseCONST.KEY.USER_EMAIL, null);
		userPassword = BasePrefManager.getInstance().getStringFromPrefs(
				context, BaseCONST.KEY.USER_PASSWORD, null);
		userName = BasePrefManager.getInstance().getStringFromPrefs(context,
				BaseCONST.KEY.USER_NAME, null);
		userId = BasePrefManager.getInstance().getStringFromPrefs(context,
				BaseCONST.KEY.USER_ID, null);
		userIcon = BasePrefManager.getInstance().getStringFromPrefs(context,
				BaseCONST.KEY.USER_ICON, null);
		rememberMe = BasePrefManager.getInstance().getStringFromPrefs(context,
				BaseCONST.KEY.USER_REMEMBER_PWD, "off");
		isAutoLogin = BasePrefManager.getInstance().getBooleanFromPrefs(
				context, BaseCONST.KEY.IS_AUTO_LOGIN, false);
		sessionId = BasePrefManager.getInstance().getStringFromPrefs(context,
				BaseCONST.KEY.USER_SEESION_ID, null);
	}

	public String getSessionId() {
		return sessionId;
	}

	public boolean isLogin() {
		return this.userStateSubject.getUserState() == LOGINED;
	}

	public String getUserName() {
		return userName;
	}

	public String getUserIcon() {
		return userIcon;
	}

	public String getUserId() {
		return userId;
	}

	public String getUserEmail() {
		return userEmail;
	}

	public String getRememberMe() {
		return rememberMe;
	}

	public String getUserPassword() {
		return userPassword;
	}

	public boolean getIsAutoLogin() {
		return isAutoLogin;
	}

	public void setSessionId(String sessionId) {
		this.sessionId = sessionId;
		BasePrefManager.getInstance().setStringToPrefs(context,
				BaseCONST.KEY.USER_SEESION_ID, sessionId);
	}

	public void setUserName(String userName) {
		this.userName = userName;
		BasePrefManager.getInstance().setStringToPrefs(context,
				BaseCONST.KEY.USER_NAME, userName);
	}

	public void setUserIcon(String userIcon) {
		this.userIcon = userIcon;
		BasePrefManager.getInstance().setStringToPrefs(context,
				BaseCONST.KEY.USER_ICON, userIcon);
	}

	public void setUserId(String userId) {
		this.userId = userId;
		BasePrefManager.getInstance().setStringToPrefs(context,
				BaseCONST.KEY.USER_ID, userId);
	}

	public void setUserEmail(String userEmail) {
		this.userEmail = userEmail;
		BasePrefManager.getInstance().setStringToPrefs(context,
				BaseCONST.KEY.USER_EMAIL, userEmail);
	}

	public void setUserPassword(String userPassword) {
		this.userPassword = userPassword;
		BasePrefManager.getInstance().setStringToPrefs(context,
				BaseCONST.KEY.USER_PASSWORD, userPassword);
	}

	public void setRememberMe(String rememberMe) {
		this.rememberMe = rememberMe;
		BasePrefManager.getInstance().setStringToPrefs(context,
				BaseCONST.KEY.USER_REMEMBER_PWD, rememberMe);
	}

	public void setIsAutoLogin(boolean isAutoLogin) {
		this.isAutoLogin = isAutoLogin;
		BasePrefManager.getInstance().setBooleanToPrefs(context,
				BaseCONST.KEY.IS_AUTO_LOGIN, isAutoLogin);
	}

	public void setSessionId(CookieStore cookieStore) {

		List<Cookie> cookies = cookieStore.getCookies();
		if (!cookies.isEmpty()) {
			for (int i = 0; i < cookies.size(); i++) {
				if (cookies.get(i).getName().equals("webpy_session_id")) {

					sessionId = cookies.get(i).getValue();
				}
			}
		}
	}

	/**
	 * 登陆Task，登陆之后根据返回值通知其注册到uerStateSubject的事件
	 * 
	 * @param context
	 * @param loginUrl
	 * @param isAutoLogin
	 */
	@SuppressLint("HandlerLeak")
	public void loginTask(final Context context, String loginUrl,
			boolean isAutoLogin) {
		handler = new Handler() {

			@Override
			public void handleMessage(Message msg) {
				switch (msg.what) {
				case LOGIN_SUCC:
					state = LOGINED;
					// UserManager.getInstance().setIsAutoLogin(true);
					log.info("logined");
					break;
				case LOGIN_FAIL:
					state = UNLOGINED;
					log.info("unlogined");
					break;
				}
				userStateSubject.setUserState(state);
			}
		};
		loginTask = new LoginTask(context, handler, loginUrl, isAutoLogin);
		loginTask.start();
	}

	public synchronized void cancleLoginTask() {
		state = UNLOGINED;
		loginTask.interrupt();
		loginTask = null;
	}

	private UserStateSubject userStateSubject = new UserStateSubject();

	/**
	 * 被观察者的引用，通过单例模式方便全局的Fragment共享。
	 */
	public UserStateSubject getUserStateSubject() {
		return userStateSubject;
	}

	/**
	 * 观察者模式
	 */
	public class UserStateSubject extends Observable {

		private int state;

		public int getUserState() {
			return state;
		}

		public void setUserState(int mState) {
			state = mState;
			setChanged();
			notifyObservers(state);
		}

	}

}
